﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MM.Common.Setup;
using MM.Common.UI.Controls;
using System.Windows.Forms;
using System.ComponentModel;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.DXErrorProvider;
using System.Data;
using MM.Common.DBBase;
using MM.Common.Base;
using DevExpress.XtraGrid.Views.Base;
using System.Drawing;
using System.Drawing.Drawing2D;
using DevExpress.XtraEditors.Controls;

namespace MM.Common.Support
{
    public partial class FrmEmpGroupSetup : FrmSetupWithItem
    {
        public FrmEmpGroupSetup()
        {
            this.InitializeComponent();
            base.gvItem = this.gvEmp;
            base.gvList = this.gvGroup;
        }

        protected override void afterInsert()
        {
            this.txtCode.Text = "";
            this.txtName.Text = "";
            this.txtInputCode1.Text = "";
            this.txtInputCode2.Text = "";
            this.ckIsValid.Checked = true;
            base.dtItem.Rows.Clear();
        }

        protected override void changeMode(bool edit)
        {
            base.changeMode(edit);
            base.pgBase.Enabled = true;
            this.OfficerEmpId.Properties.ReadOnly = !edit;
            this.txtName.Properties.ReadOnly = !edit;
            this.txtCode.Properties.ReadOnly = !edit;
            this.txtInputCode1.Properties.ReadOnly = !edit;
            this.txtInputCode2.Properties.ReadOnly = !edit;
            this.ckIsValid.Properties.ReadOnly = !edit;
            this.ValidationProvider.RemoveControlError(this.txtName);
            this.ValidationProvider.RemoveControlError(this.txtCode);
            this.ValidationProvider.RemoveControlError(this.txtInputCode1);
            this.ValidationProvider.RemoveControlError(this.txtInputCode2);
            this.ValidationProvider.RemoveControlError(this.ckIsValid);
        }

        protected override void deleteRecord()
        {
            if ((this.gvGroup.FocusedRowHandle >= 0) && (XtraMessageBox.Show("是否真的删除?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes))
            {
                DataRow focusedDataRow = base.gvList.GetFocusedDataRow();
                int paramValue = Convert.ToInt16(focusedDataRow["EMP_GROUP_ID"]);
                string[] commandtexts = new string[2];
                DataParamCol[] parms = new DataParamCol[2];
                commandtexts[0] = "UPDATE MXH_EMPLOYEE SET EMP_GROUP_ID = NULL WHERE EMP_GROUP_ID = :id ";
                parms[0] = new DataParamCol(new DataParam[] { new InputDataParam("id", paramValue) });
                commandtexts[1] = "DELETE MXHLY_DIC_EMP_GROUP WHERE EMP_GROUP_ID = :id";
                parms[1] = new DataParamCol(new DataParam[] { new InputDataParam("id", paramValue) });
                switch (SystemInfo.DbData.RunSql(commandtexts, parms))
                {
                    case 0:
                        base.dtList.Rows.Remove(focusedDataRow);
                        base.gvList.Focus();
                        this.freshDisp();
                        return;

                    case 1:
                        XtraMessageBox.Show("人员分组更新不成功!\n" + SystemInfo.DbData.ErrorMessage);
                        return;
                }
                XtraMessageBox.Show("分组删除不成功!\n" + SystemInfo.DbData.ErrorMessage);
            }
        }
        protected override bool saveRecord()
        {
            if (this.ValidationProvider.Validate())
            {
                string[] strArray;
                DataParamCol[] colArray;
                int paramValue = 0;
                string text = this.txtCode.Text;
                string str2 = this.txtName.Text;
                string str3 = this.txtInputCode1.Text;
                string str4 = this.txtInputCode2.Text;
                string str5 = this.ckIsValid.Checked ? "Y" : "N";
                decimal editValue = 0M;
                try
                {
                    editValue = (decimal)this.OfficerEmpId.EditValue;
                }
                catch
                {
                }
                int index = 0;
                string[] strArray2 = new string[base.dtItem.Rows.Count];
                for (int i = 0; i < base.dtItem.Rows.Count; i++)
                {
                    strArray2[i] = base.dtItem.Rows[i]["EMP_ID"].ToString();
                }
                if (base.isNew)
                {
                    object obj2 = null;
                    SystemInfo.DbData.ExecuteScalar("SELECT ISNULL(MAX(EMP_GROUP_ID),0) FROM MXHLY_DIC_EMP_GROUP", ref obj2);
                    paramValue = Convert.ToInt16(obj2) + 1;
                    strArray = new string[4];
                    colArray = new DataParamCol[4];
                    strArray[0] = "INSERT INTO MXHLY_DIC_EMP_GROUP (EMP_GROUP_ID ,EMP_GROUP_CODE ,INPUTCODE1 ,INPUTCODE2 ,EMP_GROUP_NAME ,USED_FLAG,OFFICER_EMP_ID) VALUES (:id ,:dm ,:srm1 ,:srm2 ,:mc ,:isvalid, :officerempid)";
                    colArray[0] = new DataParamCol(new DataParam[] { new InputDataParam("id", paramValue), new InputDataParam("dm", text), new InputDataParam("srm1", str3), new InputDataParam("srm2", str4), new InputDataParam("mc", str2), new InputDataParam("isvalid", str5), new InputDataParam("officerempid", editValue) });
                    index = 1;
                }
                else
                {
                    paramValue = Convert.ToInt16(this.gvGroup.GetFocusedDataRow()["EMP_GROUP_ID"]);
                    strArray = new string[5];
                    colArray = new DataParamCol[5];
                    DataTable dt = new DataTable();
                    string commandtext = string.Format("Select EMP_ID From MXH_EMPLOYEE Where EMP_GROUP_ID = {0}", paramValue);
                    if (SystemInfo.DbData.Retrieve(commandtext, ref dt))
                    {
                        if ((dt != null) && (dt.Rows.Count > 0))
                        {
                            strArray[0] = string.Format("UPDATE MXH_EMPLOYEE SET EMP_GROUP_ID = NULL WHERE EMP_ID in (select EMP_ID from MXH_EMPLOYEE where EMP_GROUP_ID=:group_id)", new object[0]);
                            colArray[0] = new DataParamCol(new DataParam[] { new InputDataParam("group_id", paramValue) });
                        }
                        else
                        {
                            strArray[0] = string.Format("Select EMP_ID From MXH_EMPLOYEE Where EMP_GROUP_ID = :group_id", new object[0]);
                            colArray[0] = new DataParamCol(new DataParam[] { new InputDataParam("group_id", paramValue) });
                        }
                    }
                    strArray[1] = "UPDATE MXHLY_DIC_EMP_GROUP SET EMP_GROUP_CODE = :dm ,EMP_GROUP_NAME = :mc ,INPUTCODE1 = :srm1 ,INPUTCODE2 = :srm2 ,USED_FLAG = :yn,OFFICER_EMP_ID = :officerempid WHERE EMP_GROUP_ID = :id";
                    colArray[1] = new DataParamCol(new DataParam[] { new InputDataParam("dm", text), new InputDataParam("mc", str2), new InputDataParam("srm1", str3), new InputDataParam("srm2", str4), new InputDataParam("yn", str5), new InputDataParam("id", paramValue), new InputDataParam("officerempid", editValue) });
                    index = 2;
                }
                if (strArray2.Length > 0)
                {
                    strArray[index] = string.Format("UPDATE MXH_EMPLOYEE SET EMP_GROUP_ID = :group_id WHERE EMP_ID in ({0})", string.Join(",", strArray2));
                    colArray[index++] = new DataParamCol(new DataParam[] { new InputDataParam("group_id", paramValue) });
                }
                StringBuilder builder = new StringBuilder();
                builder.AppendLine("UPDATE KTDIC_GROUP_CHANGE SET END_DATE = SYSDATE,STATUS = 'N',CHANGE_TIME = SYSDATE,CHANGE_EMP_ID=:changeempid");
                builder.AppendLine("    WHERE STATUS = 'Y' AND EMP_ID IN");
                builder.AppendLine("        (SELECT T1.EMP_ID FROM KTDIC_GROUP_CHANGE T1");
                builder.AppendLine("            INNER JOIN MXH_EMPLOYEE T2 ON T2.EMP_ID = T1.EMP_ID AND (T2.EMP_GROUP_ID IS NULL OR T2.EMP_GROUP_ID <> T1.GROUP_ID)");
                builder.AppendLine("            WHERE T2.EMP_GROUP_ID = :groupid");
                builder.AppendLine("            AND T1.STATUS = 'Y')");
                strArray[index] = builder.ToString();
                colArray[index++] = new DataParamCol(new DataParam[] { new InputDataParam("groupid", paramValue), new InputDataParam("changeempid", SystemInfo.OperId) });
                builder.Remove(0, builder.Length);
                builder.AppendLine("INSERT INTO KTDIC_GROUP_CHANGE(EMP_ID,STATUS,START_DATE,END_DATE,GROUP_ID,CHANGE_TIME,CHANGE_EMP_ID)");
                builder.AppendLine("    (SELECT EMP_ID,'Y',SYSDATE,NULL,:groupid,SYSDATE,:changeempid FROM ");
                builder.AppendLine("        (SELECT T1.EMP_ID,T2.STATUS FROM MXH_EMPLOYEE T1");
                builder.AppendLine("            LEFT JOIN KTDIC_GROUP_CHANGE T2 ON T2.EMP_ID = T1.EMP_ID AND T2.GROUP_ID = T1.EMP_GROUP_ID AND T2.STATUS = 'Y'");
                builder.AppendLine("            WHERE T1.EMP_GROUP_ID = :groupid)");
                builder.AppendLine("        WHERE STATUS IS NULL)");
                strArray[index] = builder.ToString();
                colArray[index] = new DataParamCol(new DataParam[] { new InputDataParam("groupid", paramValue), new InputDataParam("changeempid", SystemInfo.OperId) });
                if (SystemInfo.DbData.RunSql(strArray, colArray) == 0)
                {
                    if (base.isNew)
                    {
                        DataRow row = base.dtList.NewRow();
                        row["EMP_GROUP_CODE"] = text;
                        row["EMP_GROUP_NAME"] = str2;
                        row["EMP_GROUP_ID"] = paramValue;
                        row["INPUTCODE1"] = str3;
                        row["INPUTCODE2"] = str4;
                        row["USED_FLAG"] = str5;
                        row["OFFICER_EMP_ID"] = editValue;
                        base.dtList.Rows.Add(row);
                        this.gvGroup.FocusedRowHandle = base.dtList.Rows.Count - 1;
                    }
                    else
                    {
                        DataRow focusedDataRow = this.gvGroup.GetFocusedDataRow();
                        focusedDataRow["EMP_GROUP_CODE"] = text;
                        focusedDataRow["EMP_GROUP_NAME"] = str2;
                        focusedDataRow["INPUTCODE1"] = str3;
                        focusedDataRow["INPUTCODE2"] = str4;
                        focusedDataRow["USED_FLAG"] = str5;
                        focusedDataRow["OFFICER_EMP_ID"] = editValue;
                    }
                    return true;
                }
                XtraMessageBox.Show("保存数据不成功！\n原因：" + SystemInfo.DbData.ErrorMessage, "出错", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            return false;
        }

        private void txtName_TextChanged(object sender, EventArgs e)
        {
            this.txtInputCode1.Text = IME.GetInputCode(this.txtName.Text, "1");
            this.txtInputCode2.Text = IME.GetInputCode(this.txtName.Text, "2");
        }


        protected override void freshDisp()
        {
            DataRow focusedDataRow = this.gvGroup.GetFocusedDataRow();
            if (focusedDataRow != null)
            {
                this.OfficerEmpId.EditValue = focusedDataRow["OFFICER_EMP_ID"];
                this.txtCode.Text = focusedDataRow["EMP_GROUP_CODE"].ToString();
                this.txtName.Text = focusedDataRow["EMP_GROUP_NAME"].ToString();
                this.txtInputCode1.Text = focusedDataRow["INPUTCODE1"].ToString();
                this.txtInputCode2.Text = focusedDataRow["INPUTCODE2"].ToString();
                this.ckIsValid.Checked = focusedDataRow["USED_FLAG"].ToString() == "Y";
                base.dtItem.Rows.Clear();
                string commandtext = "SELECT EMP_ID ,EMP_CODE ,EMP_NAME FROM MXH_EMPLOYEE WHERE EMP_GROUP_ID = :group_id ORDER BY EMP_CODE ASC ";
                DataParamCol parm = new DataParamCol(new DataParam[] { new InputDataParam("group_id", focusedDataRow["EMP_GROUP_ID"]) });
                SystemInfo.DbData.Retrieve(commandtext, parm, ref this.dtItem);
                base.dtItem.PrimaryKey = new DataColumn[] { base.dtItem.Columns["EMP_ID"] };
            }
        }

        protected override void getChoiceItem()
        {
            int[] numArray = new int[3];
            numArray[1] = 30;
            numArray[2] = 100;
            new FrmMulSelFromGrid(base.dtItemAll, new string[] { "标识", "代码", "姓名" }, numArray, "人员选择", ref this.dtItem).ShowDialog(this);
        }

        protected override void getItemAll()
        {
            base.dtItemAll.Clear();
            SystemInfo.DbData.Retrieve("SELECT EMP_ID ,EMP_CODE ,EMP_NAME FROM MXH_EMPLOYEE WHERE USED_FLAG = 'Y' ORDER BY EMP_CODE", ref this.dtItemAll);
            base.dtItemAll.PrimaryKey = new DataColumn[] { base.dtItemAll.Columns["EMP_ID"] };
        }

        private void gvEmp_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            DataRow focusedDataRow = this.gvEmp.GetFocusedDataRow();
            if (focusedDataRow != null)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine("SELECT T2.EMP_GROUP_NAME,T1.START_DATE,T1.END_DATE,T1.STATUS FROM KTDIC_GROUP_CHANGE T1");
                builder.AppendLine("    INNER JOIN MXHLY_DIC_EMP_GROUP T2 ON T2.EMP_GROUP_ID = T1.GROUP_ID");
                builder.AppendFormat("    WHERE T1.EMP_ID = {0}", focusedDataRow["EMP_ID"]);
                builder.AppendLine("    ORDER BY T1.START_DATE DESC");
                DataTable dt = new DataTable();
                SystemInfo.DbData.Retrieve(builder.ToString(), ref dt);
                this.EmpGroupChangeLogGrid.DataSource = dt;
            }
        }

        public override bool Init()
        {
            bool flag = false;
            if (base.Init())
            {
                base.dtList = new DataTable();
                SystemInfo.DbData.Retrieve("SELECT EMP_GROUP_ID ,EMP_GROUP_CODE ,INPUTCODE1 ,INPUTCODE2 ,EMP_GROUP_NAME ,USED_FLAG ,OFFICER_EMP_ID FROM MXHLY_DIC_EMP_GROUP ORDER BY EMP_GROUP_CODE", ref this.dtList);
                base.nbiChoice.Caption = "人员";
                base.InitData();
                this.OfficerEmpId.Properties.DataSource = base.dtItem;
                flag = true;
            }
            return flag;
        }
    }
}
